<template>
  <div class="search_suggest">
    <van-cell
      v-for="(text,index) in suggestList"
      v-show="suggestList[0]!==null||suggestList.length!=0"
      :key="index"
      icon="search"
      @click="$emit('updateSearch',text,true)"
    >
      <div
        slot="title"
        v-html="replaceFn(text)"
      ></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggests } from '@/api/search'
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggest',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestList: []
    }
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {
    searchText: {
      // handler (value) {
      //   console.log(value)
      //   this.getSearchSuggestsHandler(value)
      // },
      handler: debounce(function (value) {
        console.log(value)
        this.getSearchSuggestsHandler(value)
      }, 1000),
      immediate: true
    }
  },
  created () { },
  mounted () { },
  methods: {
    async getSearchSuggestsHandler (p) {
      const { data } = await getSearchSuggests(p)
      this.suggestList = data.data.options
      console.log(data.data.options)
    },
    replaceFn (text) {
      if (!text) return
      const highLightStr = `<span class="highlight">${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, highLightStr)
    }
  }
}
</script>

<style scoped lang="less">
.search_suggest {
  /deep/.highlight {
    color: skyblue;
  }
}
</style>
